﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
//New and needed
using IM.Common.ServiceContract;
using IM.Domain.Entities;
using IM.Common.DTOS;
using IM.Domain.Repository;
using IM.Domain.AppServices;

namespace IM.Domain.Services
{
    public class PersonService:ServiceBase, IPersonService
    {


        #region Helper methods
        private PersonDTO PersonToDTO(PersonEntity person)
        {
            return new PersonDTO
            {
                IdPerson = person.ID,
                FirstName = person.FirstName,
                MiddleName = person.MiddleName,
                IdIdentification = person.IdIdentification
            };
        }
        #endregion

        #region IPersonService Members

        public PersonDTO CreateNewPerson(PersonDTO personDTO)
        {
            return ExecuteCommand(locator => this.CreateNewPersonCommand(locator, personDTO));
        }

        public PersonDTOS GetAll()
        {
            return ExecuteCommand(locator => this.GetAllCommand(locator));
        }

        private PersonDTO CreateNewPersonCommand(IRepositoryLocator locator, PersonDTO dto)
        {
            var person = PersonEntity.Create(locator, dto);
            return PersonToDTO(person);
        }

        private PersonDTOS GetAllCommand(IRepositoryLocator locator)
        {
            var result = new PersonDTOS 
            {
                Persons = new List<PersonDTO>()
            };

            locator.GetAll<PersonEntity>().ToList().ForEach(p => result.Persons.Add(PersonToDTO(p)));

            if (result.Persons.Count == 0)
            {
                ServiceLocator.Instance().Notifier.AddWarning(Common.Message.BusinessWarningENUM.Default, "No customer instances were found");
            }

            return result;
        }
        #endregion
    }
}
